﻿using QRCoder;
using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace CoreModule.Converters
{
    /// <summary>
    /// 字符转二维码图片 没有使用
    /// </summary>
    public class StringToQRCodeImageConverter : IValueConverter
    {
        public int PixelsPerModule { get; set; } = 20;
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return GenerateQRCode(value.ToString());
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private BitmapImage GenerateQRCode(string content)
        {
            // 创建 QRCodeGenerator 对象并生成 QRCodeData 对象
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M);
            // 将 QRCodeData 对象转换为 Bitmap 对象
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(PixelsPerModule);
            // 将 Bitmap 对象转换为 BitmapImage 对象
            MemoryStream memoryStream = new MemoryStream();
            qrCodeImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
            memoryStream.Position = 0;
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memoryStream;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            return bitmapImage;
        }
    }
}
